#/usr/bin/python
import redis
import time
class Taskschedule():

    def __init__(self, r):
        self.r = r
        self.NodeInfo = 'machineInfo'
    def  cleanDeadNode(self):
        dict = r.hgetall(self.NodeInfo)
        #print dict
        for (k,item) in dict.items():
            try:
                temp = r.get(k)
                if temp is None:
                    r.hdel(self.NodeInfo, k)
                    print 'delete' + item
            except Exception, exception:
                print k,exception

    def publish(self):
        dict = r.hgetall(self.NodeInfo)
        #print dict
        for (k, Ditem) in dict.items():
            try:
                item = eval(Ditem)
                #
                if item['MemUsed']/item['MemTotal'] > 0.75 or float(item['loadarv']) > 75 :
                    print item['MemUsed']/item['MemTotal'] > 0.75,item['MemUsed']/item['MemTotal'],float(item['loadarv'])  ,float(item['loadarv']),float(item['loadarv']) > 75
                    continue
                command = r.brpop(k+'list',timeout=1)
                print command
                if command is not None:
                    print command
                    p = r.publish('queue', command)
            except Exception, exception:
                print exception
                pass


    def run(self):
        while(True):
            self.cleanDeadNode()
            self.publish()
            time.sleep(1)
            # channel post

if __name__ == '__main__':
    pool = redis.ConnectionPool(host='localhost',port=6379, db=0)
    r = redis.StrictRedis(connection_pool=pool)
    ts = Taskschedule(r)
    ts.run()